# coding:utf-8

# 2018.08.28 15:30:16 中国标准时间
# Embedded file name: luat.pyc
import serial
import time
from cfghelper import Group, FullMatch, ReMatch
import globals
import sys
import datetime
import re
# import test


class LuatModule:

    def __init__(self, port='COM1', baudrate=115200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=0):
        try:
            self.serialport = serial.Serial(
                port=port, baudrate=baudrate, bytesize=bytesize, parity=parity, stopbits=stopbits, timeout=0)
        except:
            # test.diag_exit()
            sys.exit(5)
        self.sbuf = ''
        self.exceptReponse = ''

    def initBuffer(self):
        self.sbuf = ''

    def setExceptResponse(self, exceptReponse):
        self.exceptReponse = exceptReponse

    def consumeReponse(self, data):
        if isinstance(self.exceptReponse, FullMatch):
            self.sbuf = self.sbuf + data
            foundPos = self.sbuf.find(self.exceptReponse.getNeedle())
            if foundPos != -1:
                self.sbuf = self.sbuf[foundPos:foundPos +
                                      len(self.exceptReponse.getNeedle())]
                return 'Success'
            return False
        elif isinstance(self.exceptReponse, ReMatch):
            self.sbuf = self.sbuf + data
            foundPos = self.exceptReponse.check(self.sbuf)
            if foundPos:
                return 'Success'
            return False
        self.sbuf = self.sbuf + data
        reponseArray = self.sbuf.split('\r\n')
        #self.sbuf = reponseArray[len(reponseArray) - 1]
        del reponseArray[len(reponseArray) - 1]
        for i in reponseArray:
            if isinstance(self.exceptReponse, (str, unicode)):
                if i == self.exceptReponse:
                    return 'Success'
            elif self.exceptReponse.check(i):
                return 'Success'
            if i == 'ERROR':
                return "Fail"

        return False

    def testCmd(self, CmdType, request, exceptReponse, timeout, ErrLev, passed, failed, suceseCmdtime, failCmdtime, succes_test_time, failed_test_time):
        self.serialport.read(1024)
        self.initBuffer()
        if CmdType == 0:
            self.setExceptResponse(exceptReponse)
            self.serialport.write(request + '\r\n')
            waitTime = timeout * 10
            while True:
                result = self.consumeReponse(self.serialport.read(1024))
                # globals.getLogger().logline(self.sbuf)
                if result == False:
                    time.sleep(0.1)
                    waitTime -= 1
                    if waitTime <= 0:
                        if ErrLev == 1:
                            globals.getLogger().logline(self.sbuf)
                            return self.sbuf
                        else:
                            break
                    continue
                if result == 'Success':
                    globals.getLogger().logline(self.sbuf)
                    return 'OK'

                if ErrLev == 1:
                    globals.getLogger().logline(self.sbuf)
                    return self.sbuf
                else:
                    break
        elif CmdType == 1:
            if isinstance(request, int):
                time.sleep(request/1000.0)
            else:
                return 'ERROR'
        elif CmdType == 2:
            if isinstance(request, (str, unicode)):
                self.setExceptResponse(exceptReponse)
                self.serialport.write(request)
                waitTime = timeout * 10
                if exceptReponse == "":
                    return 'OK'
                else:
                    while True:
                        result = self.consumeReponse(
                            self.serialport.read(1024))
                        if result == False:
                            time.sleep(0.1)
                            waitTime -= 1
                            if waitTime <= 0:
                                if ErrLev == 1:
                                    return self.sbuf
                                else:
                                    break
                            continue
                        if result == 'Success':
                            return 'OK'
                        if ErrLev == 1:
                            return self.sbuf
                        else:
                            break
            else:
                return 'ERROR'
            pass
        elif CmdType == 3:
            if not str(exceptReponse).isdigit():
                exceptReponse = 1
            for reTestN in range(0, int(exceptReponse)):
                if isinstance(request, list):
                    for i in request:

                        if len(i) != 5:
                            err_info = u''' ********************************************************
                            测试命令不符合规则:
                            1.	修改配置文件格式为[命令类型, '命令字符', '结果', 超时时间, 错误等级]，
                            2.	"命令类型" 分为4种，0：AT指令 1：延迟 2：数据 3:嵌套运行另外的cmdlist’
                            3.	"错误等级" 分为2种，0忽略错误继续运行，1停止运行
                            注意:
                                1,当"命令类型" 为1 的时候 "命令字符" 为延迟时间(单位ms)
                                2,当"命令类型" 为3 的时候,嵌套的里面的命令也要和本格式相同 
                            本次运行结束
                            *********************************************************
                            '''
                            # globals.getLogger().logPrefixln('INFO',err_info)
                            # globals.getLogger().logPrefixln('INFO', 'AT指令已经成功测试了%d条, %d条失败' % (len(passed), len(failed)))
                            break
                        elif i[0] == 0:
                            globals.getLogger().logPrefixln(
                                'INFO', 'Testing %s, timeout: %d' % (i[1], i[3]))
                        elif i[0] == 1:
                            globals.getLogger().logPrefixln(
                                'INFO', 'delay time %d' % (i[1]))
                        elif i[0] == 2:
                            globals.getLogger().logPrefixln('INFO', 'send data')
                        elif i[0] == 3:
                            suceseCmdtime.append(
                                datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                            #succes_test_time.append(str(time.clock() - time1))
                            #globals.getLogger().logPrefixln("test time : ", str(time.clock() - time1))
                            passed.append("***Enter embed Test***")
                            globals.failed_path.append(i[5])
                            globals.getLogger().logPrefixln('INFO', 'Testing embed Cmd')

                        time1 = time.clock()
                        testResult = self.testCmd(
                            i[0], i[1], i[2], i[3], i[4], passed, failed, suceseCmdtime, failCmdtime, succes_test_time, failed_test_time)

                        cmdName = ""
                        if (testResult == "OK"):
                            if i[0] == 0:
                                cmdName = i[1]
                            elif i[0] == 1:
                                cmdName = "***Delay:" + str(i[1]) + "ms***"
                            elif i[0] == 2:
                                cmdName = "***Send data:" + str(i[1]+"***")
                            elif i[0] == 3:
                                globals.failed_path.pop()
                                cmdName = "***Exit embed Test***"
                            suceseCmdtime.append(
                                datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                            succes_test_time.append(str(time.clock() - time1))
                            if i[0] == 2 or i[0] == 0:
                                globals.getLogger().logPrefixln("test time : ", str(time.clock() - time1))
                            passed.append(cmdName)
                        else:
                            if testResult == '':
                                testResult = "timeout"
                            tempRes = ""
                            for Ti in testResult:
                                if ord(Ti) < 32 and ord(Ti) > 126:
                                    t = hex(ord(Ti))
                                else:
                                    t = Ti
                                tempRes = tempRes + t
                                pass
                            globals.getLogger().logPrefixln('ERROR',
                                                            'Command %s failed, error reason: %s' % (i[0], tempRes))
                            if i[0] == 0:
                                cmdName = i[1]
                            elif i[0] == 1:
                                cmdName = "***Delay:" + str(i[1]) + "ms***"
                            elif i[0] == 2:
                                cmdName = "***Send data:" + str(i[1]+"***")
                            elif i[0] == 3:
                                globals.failed_path.pop()
                                cmdName = "***Exit embed Test***"
                            if len(i) > 4 and i[4] == 1 and cmdName != "***Exit embed Test***":
                                failCmdtime.append(
                                    datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                                failed_test_time.append(time.clock() - time1)
                                failed.append('/'.join(globals.failed_path)+'/'+cmdName)
                                globals.error_msg.append(tempRes)
                            if ErrLev == 1:
                                return "ERROR"
                            else:
                                break
            return "OK"
        return "OK"

# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2018.08.28 15:30:16 中国标准时间
